#!/usr/bin/perl
use strict;
use abs;

if($#ARGV!=1){
    die "syntax: plot_pred.pl file maxdiff\n";
}
my ($file_param,$maxdiff)=@ARGV;
$file_param=~/file(.+)Nsamples/;

my $file_dat=$1;

open(IN_PARAM,$file_param) or die "$file_param $!\n"; 
my $nlines=int(`wc -l $file_dat`);

my @tabl;
my ($f,$lp,$lm);
my ($length_in_sample);
my $i;
my @files_out;
while(<IN_PARAM>){
    chomp;
    ($length_in_sample,$f,$lp,$lm)=split(/\s+/);
    my $file_OUT_insample=$file_param.".predIN-$length_in_sample";
    open(OUT_insample,">$file_OUT_insample") or die "$!\n";
    for($i=0;$i<$length_in_sample;$i++){
	print OUT_insample "$i ",$f*exp($lp*$i)+(1-$f)*exp($lm*$i),"\n";
    }
    close OUT_insample;

    my $file_OUT_outsample=$file_param.".predOUT-$length_in_sample";
    push(@files_out,$file_param.".predOUT-$length_in_sample");
    open(OUT_outsample,">$file_OUT_outsample") or die "$!\n";
    for($i=0;$i<$nlines;$i++){
	print OUT_outsample "$i ",$f*exp($lp*$i)+(1-$f)*exp($lm*$i),"\n";
    }
    close OUT_outsample;
}
 
open(IN_DAT,$file_dat) or die "$file_dat $!\n";
my @data=<IN_DAT>;
for($i=0;$i<=$#data;$i++){
    chomp($data[$i]);
}

my $t0;
my $tpred;
my $line;
my $file;

open(OUT_tpred,">$file_dat-tpred_vs_t0-$maxdiff.dat") or die "$!\n";
foreach $file (@files_out){
#    print "$file\n";
    $file=~/OUT-(\d+)$/;
    $t0=$1;
    if($t0=~/dat$/){
#	print "t0=$t0\n";
	next;
    }
    open(IN_pred,$file) or die "$file\n";
    for($i=0;$i<$t0;$i++){
	$line=<IN_pred>;
    }
    $tpred=$nlines;
    while(<IN_pred>){
	chomp;
	@tabl=split(/\s+/);
	if(&abs(($tabl[1]-$data[$i])/$tabl[1])>$maxdiff){
	    $tpred=$i;
	    last;
	}
	else{
	    $i++;
	}
    }
    print OUT_tpred "$t0 $tpred\n";
    close IN_pred;
}
close OUT_tpred;

